import { useI18n } from "vue-i18n";
import { onBeforeMount, ref, computed } from "vue";
import { useGlobalStore } from "../store/global";
import { useEventBus, useScriptTag } from "@vueuse/core";
import * as MITO from "@zhj1214/qdjk-web";
import { showLoadingToast as LoadingToast } from "vant";
// import Compressor from "compressorjs";

/**
 * @description: 桥接版本时是否过校验,
 * 1. 相同版本,或者高版本返回 true
 * 2. 没有传入版本号,就代表不教研 true
 * @param {any} standard 兼容标准 对象类型,key: packagePrefix的值 value:是具体的版本号
 * @param {any} defaultValue 默认值.没有传版本,就使用默认值
 * @return {*} true 通过,false 不通过
 * @author: zhj1214
 */
export const bridgeVersionCheck = (
  standard: any = {},
  defaultValue = false
) => {
  const globalStore = useGlobalStore();
  // 1. 获取版本号
  const value = standard[globalStore.packagePrefix];
  // 1.1 不通过: 传入一个大的版本号不靠谱,使用 false 最好
  if (value === "false") {
    return false;
  }
  // 2. 版本比较
  else if (value) {
    const compareVersion = compare(globalStore.packageId, value) || -1;
    console.log("bridgeVersionCheck: 版本兼容_", compareVersion);
    if (!validatenull(compareVersion) && compareVersion >= 0) {
      return true;
    } else {
      return false;
    }
  }
  // 没有传入版本号: defaultValue
  else {
    return defaultValue;
  }
};

/**
 * @description: 自定义 closeToast 解决,请求结束以后closeToast清除延迟问题
 * @param {*} options
 * @author: zhj1214
 */
let isHasLoading: any = null; // 有没有正在展示的 showLoadingToast 实例
export function closeLoadingToast() {
  if (!isHasLoading) return;
  isHasLoading.close();
  isHasLoading = null;
}
/**
 * @description: 自定义 showToast 解决,请求结束以后closeToast清除延迟问题
 * @param {*} options
 * @author: zhj1214
 */

export function showLoadingToast(options: any) {
  // 这里可以自定义你的逻辑，例如添加默认配置、处理选项等
  // const defaultOptions = {
  //   duration: 3000,
  //   message: "This is a custom toast",
  //   ...options,
  // };
  if (isHasLoading) {
    isHasLoading.close();
  }
  isHasLoading = LoadingToast(options);
  return isHasLoading;
}

/**
 * @description: 刷新当前页面
 */
export const reloadPage = () => {
  if (!process.client) return;
  try {
    // 方式一
    const router = useRouter();
    router.go(0);
  } catch (error) {
    // 方式二
    window.location.reload();
  }
};

/**
 * @description: 跳转登录页面
 * 1. token没有获取到; 3 秒后:stroe 中没有 token;
 * 2. 接口 403 跳转登录页面
 */
export const jumpLogin = () => {
  // 1. 删除本地token
  const globalStore = useGlobalStore();
  globalStore.removeLocalToken();
  // 2. 跳转app 界面
  bridge.onAppLogin();
};

/**
 * @description: 对字符串进行base64编码
 * @param {*} str 传入字符串
 * @return {*} 编码结果
 */
export const base64Encode = (str: string) => {
  let base64EncodedString = btoa(unescape(encodeURIComponent(str)));
  return base64EncodedString;
};

/**
 * @description: 是不是 Android 设备
 */
export const isAndroid = computed(() => {
  if (process.client) {
    let u = navigator.userAgent;
    return u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //g
  }
});

/**
 * @description: 是不是 iOS 设备
 */
export const isiOS = computed(() => {
  if (process.client) {
    let u = navigator.userAgent;
    return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
  }
});

/**
 * @description: 路由前进后退（默认返回上一级）
 * @param {*} level -1
 * @param {*} isOnlyBackApp 是否仅仅只返回 App
 */
export const navigateBack = (level = -1, isOnlyBackApp = false) => {
  if (process.client) {
    if (!isOnlyBackApp) {
      if (
        window &&
        window.history.state.back &&
        window.history.state.back !== window.history.state.current
      ) {
        const router = useRouter();
        router.go(level);
      } else {
        navigateI18nTo({
          path: "/mvp/coin/coin",
        });
      }
    } else {
      bridge.onAppBack("0");
    }
  }
};

/**
 * @description: i18n路由跳转
 */
export const navigateI18nTo = async (params: any) => {
  // 方案一
  // const router = useRouter(); // 路由跳转
  // const localePath = useLocalePath(); // 路由跳转
  // router.push(localePath(params));
  // 方案二
  const localeRoute = useLocaleRoute();
  const globalStore = useGlobalStore();
  const linkPath = computed(() => {
    const route = localeRoute(params.path, globalStore?.$state.language); // 第二个参数保证跳转的页面使用的都是指定的语言
    return route != null ? route.path : "/";
  });
  console.log(params, "--linkPath--", linkPath.value);
  navigateTo({
    path: linkPath.value,
    query: params.query,
  });
  // router.push(linkPath.value);
};

/**
 * @description: tabbar 页面跳转
 * @param {string} page 页面的 name
 */
export const switchTabBar = (page: string) => {
  const switchTabBarEmit = useEventBus("tab-bar-jump-on");
  const globalStore = useGlobalStore();
  const idx = globalStore.$state.tabBarPages.indexOf(page);
  if (idx >= 0) {
    switchTabBarEmit.emit(idx);
  }
};

/**
 * @description: 如果链接是当前项目路由页面，调用此函数
 * @param {string} thirdUrl
 * @author: zhj1214
 */
export const jumpLocalH5PageRoute = (thirdUrl: string) => {
  // 获取当前 URL 对象
  const url = new URL(thirdUrl);
  // 获取参数对象
  const params = new URLSearchParams(url.search);
  // 创建一个空对象来存储解析后的参数
  const parsedParams: any = {};
  // 遍历参数对象并将其存储在解析后的对象中
  for (const [key, value] of params.entries()) {
    parsedParams[key] = value;
  }
  console.log(url, "--url跳转本项目的页面--", parsedParams);

  navigateI18nTo({
    path: url.pathname.replace("/fx", ""),
    query: parsedParams,
  });
};

/**
 * @description: 如果链接是当前项目地址，通过 url 跳转，调用此函数
 * @param {string} thirdUrl
 * @author: zhj1214
 */
export const jumpLocalH5PageUrl = async (thirdUrl: string) => {
  const globalStore = useGlobalStore();
  let token = globalStore.$state.token
    ? `&token=${globalStore.$state.token}`
    : "";
  thirdUrl += `?language=${globalStore.$state.language}&packageId=${globalStore.$state.packageId}${token}&hiddenBar=1`;
  await navigateTo(thirdUrl, {
    external: true,
  });
};

export const goDownload = () => {
  if (process.client) {
    try {
      const u = navigator.userAgent;
      const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //android终端

      if (!isAndroid) {
        return (window.location.href =
          "https://apps.apple.com/app/btcdana-trading-online/id1641836061");
      }

      window.location.href =
        "https://play.google.com/store/apps/details?id=com.btcdana.online&hlid&hl=en&shortlink=74dc6077&c=BtcInvite-h5&pid=QR_code&source_caller=ui";
    } catch (e) {
      console.log(e);
    }
  }
};
/*
 * 登录的统一hook
 * */
export const useSignup = () => {
  let { locale } = useI18n();
  // id为邀友者id
  return (id: string | number = "") => {
    try {
      if (!locale.value || locale.value === "en_US") {
        locale.value = "en";
      }
      if (id !== "") {
        id = `id=${id}`;
      }
      window.location.href = `https://reg.forexdana.trade/download/${locale.value}/#/share/email?${id}`;
    } catch (e) {
      console.log(e);
    }
  };
};

/**
 * 区分调用浏览器的是什么设备
 */
export const useUserAgent = () => {
  const agent = ref<string>();
  const setAgent = (newAgent: string) => (agent.value = newAgent);

  onBeforeMount(() => {
    const u = navigator.userAgent;
    const isWeixin = u.toLowerCase().indexOf("micromessenger") !== -1; // 微信内
    const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1; //android终端
    const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

    isWeixin && (agent.value = "wx");
    isAndroid && (agent.value = "android");
    isIOS && (agent.value = "ios");
  });

  return [agent, setAgent];
};

/**
 * 客户端与前端通讯, 约定通过url传参, data=ASDASD, 使用base64加密
 * 例如: data={profit:0.32}
 */
export const getQueryData = () => {
  try {
    const route = useRoute();
    const search =
      route.query.data && (route.query.data as string).split("=")[1];
    return JSON.parse(base64Encode(search || ""));
  } catch (e) {
    console.log(e);
  }
};

/**
 * @description: 千位符表示
 * @param {number} num
 * @return {*}
 */
export const toThousands = (num: number | string) => {
  var numStr = (num || 0).toString();
  let decimal = "";
  if (numStr.includes(".")) {
    const arr = numStr.split(".");
    numStr = arr[0];
    decimal = arr[1];
  }
  return `${numStr.replace(/(\d)(?=(?:\d{3})+$)/g, "$1,")}${
    decimal && "."
  }${decimal}`;
};

/**
 * @description: 保留几位小数字
 * @param {number | string} val
 * @param {number} count
 * @param {boolean} isRound 默认只截取不会四舍五入
 * @param {boolean} isRetention 默认保留小数点和 0
 * @return {*} 结果
 */
export const decimalToLength = (
  val: string | number,
  count = 2,
  isRound = false,
  isRetention = true
) => {
  // 1. 转成 string
  let valStr = (val || 0).toString();
  // 2. 是否包含小数点
  const l = valStr.indexOf(".");
  if (l > 0) {
    if (count > 0) {
      if (!isRound) {
        let afterStr = valStr.substring(l, l + count + 1);
        // 不够位数:补 0
        if (afterStr.length < count) {
          for (let index = 0; index < count - afterStr.length; index++) {
            afterStr += "0";
          }
        }
        return valStr.split(".")[0] + afterStr;
      } else {
        return parseFloat(valStr).toFixed(count);
      }
    } else {
      return valStr.split(".")[0];
    }
  }
  // 例如: .23
  else if (l === 0) {
    return `0${valStr.substring(l, l + count + 1)}`;
  }
  // 不包含
  else {
    let suffix = "";
    for (let index = 0; index < count; index++) {
      suffix += "0";
    }
    return `${valStr}${isRetention && count > 0 ? "." + suffix : ""}`;
  }
};

/**
 * @description: 用户昵称格式转换
 * @param {string} name 用户昵称
 * @param {*} type 1. 包含***  2.最长 11 位,超过...展示
 * @return {*} 昵称
 * @author: zhj1214
 */
export const userNameToFormat = (name: string, type = 1, nullStr = "--") => {
  if (!name) return nullStr;
  if (type == 1) {
    if (name.length >= 6) {
      return name.slice(0, 3) + "**" + name.slice(-3);
    } else {
      return name.slice(0, 3) + "**";
    }
  } else if (type == 2) {
    let str = "";
    str = name.substring(0, 11);
    if (name.length > 11) {
      str += "...";
    }
    return str;
  }
  return nullStr;
};

/**
 * @description: 解析接口返回的数据
 * @param {*} reponse 原始数据
 * @param {*} call 回调函数
 * @param {*} key 数据字段名
 * @param {*} code 默认 0 代表成功
 * @return {*} 返回数据
 * @author: zhj1214
 */
export function reponseIntercept(
  reponse: any,
  call?: Function,
  key = "data",
  code = 200
) {
  if (reponse && reponse.code === code) {
    call && call(reponse[key] || reponse);
    return reponse[key] || reponse;
  } else {
    call && call(false, reponse);
    return false;
  }
}
/**
 * 各环境OSS地址
 */
const getImgOss: any = () => {
  const u = {
    dev: "https://asset.okmax.vip",
    test: "https://asset.okmax.vip",
    prep: "https://asset.btcdana.vip" || "https://asset.onetrader.online",
    prod: "https://asset.btcdana.vip" || "https://asset.onetrader.online",
  }[useRuntimeConfig().public.WEB_NODE_ENV as EnvInfo];
  return () => {
    // 新加坡服务器
    if (process.client) {
      if (window && window.location.host.includes("bdc-sg")) {
        return "https://asset-sg.btcdana.asia";
      }
    }
    return u;
  };
};
// 获取图片前缀,传入 url 即可拼接
let getImgOssValue = "";
export const getImagePrefix = (url?: string) => {
  if (!getImgOssValue) getImgOssValue = getImgOss()();
  // console.log("getImgOssValue--", getImgOssValue);
  if (url) {
    return getImgOssValue + url;
  } else {
    return getImgOssValue;
  }
};
/**
 * 各环境host地址
 */
export const origin = {
  // dev:  "http://localhost:3000",
  dev: "https://test-bdc.btcdana.org/fx",
  devSG: "https://bdc-sg.btcdana.org",
  test: "https://test-bdc.btcdana.org",
  prep: "https://pre-bdc.btcdana.org",
  prod: "https://bdc.btcdana.org",
};

let getOrigin: any = () => {
  const env = useRuntimeConfig().public.WEB_NODE_ENV;
  let hostUrl = origin[env as EnvInfo];
  // 新加坡服务器
  if (process.client) {
    if (window && window.location.host.includes("bdc-sg")) {
      hostUrl = origin["devSG"];
    }
  }
  const prefix =
    process.env.NODE_ENV !== "development" ? "/fx" : env != "dev" ? "/fx" : "";
  return () => {
    return { hostUrl, prefix };
  };
};
let getOriginValue: any = "";
export const getOriginUrl = (path: string) => {
  if (!getOriginValue) getOriginValue = getOrigin()();
  return () => `${getOriginValue.hostUrl}${getOriginValue.prefix}${path}`;
};

/**
 * @description: 动态加载 Script 脚本
 * @param {string} url
 * @param {Function} call 回调函数
 * @param {boolean} isRetry 默认,加载失败,需要重试
 * @param {boolean} isLocal 是不是当前服务器资源
 * @return {*}
 * @author: zhj1214
 */
let loadScriptMap = new Map(); // 主要用于计数和去重
export const loadScript = (
  url: string,
  call: any,
  isRetry = true,
  isLocal = true
) => {
  if (!url || !process.client) return;
  // 1. 下载文件
  const swiperUrl = isLocal ? getOriginUrl(url)() : url;
  const { load, unload } = useScriptTag(swiperUrl, (el: HTMLScriptElement) => {
    loadScriptMap.delete(swiperUrl);
    call && call(el);
  });
  // 2. 捕获错误,失败会重试 3 次
  if (isRetry) {
    if (!loadScriptMap.get(swiperUrl)) loadScriptMap.set(swiperUrl, 0);
    load()
      // .then((res) => {
      //   console.log("-------loadScript---done--", call);
      //   call && call(res);
      // })
      .catch((error: any) => {
        console.error("-------loadScript-----", error);
        let cs = loadScriptMap.get(swiperUrl);
        loadScriptMap.set(swiperUrl, Number(cs) + 1);
        // 2.1 卸载
        unload();
        // 2.2 再次加载
        if (Number(cs) + 1 <= 3) {
          loadScript(url, call);
          console.error(
            `--catch--网络异常,${url}资源下载失败,正在重试${loadScriptMap.get(
              swiperUrl
            )}次`,
            error
          );
        } else {
          MITO.log({
            message: `loadScript=>网络异常,${url}资源下载失败`,
            tag: "手动上报",
            level: "high",
            ex: "手动上报",
          });
          call(false);
          // 网络差提示
          const showToastEmit = useEventBus("showToast-emit");
          showToastEmit.emit("common.wlycqcxjr");
        }
      });
  } else {
    load();
  }
};

/**
 * @description: 动态获取public目录下文件的oss地址
 * svg 格式不行
 * 本地 http://192.168.88.45:3000/image/coin/trendImg.png
 * 线上 https://bdc.btcdana.org/fx/image/coin/trendImg.png
 * @param {any} val
 * @return {*} val
 * @author: zhj1214
 */
export const getOssFileUrl = (val: any) => {
  // if (!process.server) {
  if (typeof val === "object") {
    // const origin = (window.location && window.location.origin) || "";
    // // const confg = useRuntimeConfig();
    // // console.log("--getOssFileUrl--", process.env.NODE_ENV);
    // const prefix = process.env.NODE_ENV !== "development" ? "/fx" : "";
    // if (typeof getOrigin != "object") getOrigin = getOrigin()();
    if (!getOriginValue) getOriginValue = getOrigin()();
    for (const key in val) {
      if (Object.prototype.hasOwnProperty.call(val, key)) {
        val[
          key
        ] = `${getOriginValue.hostUrl}${getOriginValue.prefix}${val[key]}`;
      }
    }
  }
  return val;
  // }
  // return {};
};

/**
 * @description: 节流
 * @param {*} func 要执行的函数
 * @param {*} limit 时间
 * @param {*} isDelayExecution 是否需要，延迟执行一次
 * @return {*} function
 * @author: zhj1214
 */
export const throttle = function <T extends (...args: any[]) => any>(
  func: T,
  limit: number,
  isDelayExecution = false
): (...args: Parameters<T>) => void {
  if (!process.client) return () => {};
  let inThrottle: boolean;
  let lastFunc: number;
  let lastRan: number;

  return function (...args: Parameters<T>) {
    if (!inThrottle) {
      func(...args);
      lastRan = Date.now();
      inThrottle = true;
    } else {
      clearTimeout(lastFunc);
      lastFunc = window.setTimeout(function () {
        if (Date.now() - lastRan >= limit) {
          if (isDelayExecution) {
            func(...args);
            lastRan = Date.now();
          } else {
            inThrottle = false;
          }
        }
      }, Math.max(limit - (Date.now() - lastRan), 0));
    }
  };
};

/**
 * @description: 防抖
 * @param {*} function 执行函数
 * @param {*} delay 延迟时间
 * @param {*} isDelayexec 延迟以后是否执行(默认不执行)
 */
export const debounce = function <T extends (...args: any[]) => void>(
  func: T,
  delay: number,
  isDelayexec = false
): (...args: Parameters<T>) => void {
  if (!process.client) return () => {};

  let timeoutId: number | undefined = undefined;
  let isRun: boolean = false;

  return function (...args: Parameters<T>) {
    // 1. 清除之前的延迟调用
    if (timeoutId !== undefined && timeoutId !== null) {
      clearTimeout(timeoutId);
      isRun = false;
    } else {
      // 1.2 立即执行
      func(...args);
      isRun = true;
    }
    // 2. 延迟
    timeoutId = window.setTimeout(() => {
      if (!isRun && isDelayexec) func(...args);
      clearTimeout(timeoutId);
      timeoutId = undefined;
      isRun = false;
    }, delay);
  };
};

/**
 * @description: 哈希
 * @param {string} str
 * @return {*}
 * @author: zhj1214
 */
export function hashCode(str: string): number {
  let hash = 0;
  if (str.length == 0) return hash;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash;
  }
  return hash;
}

/**
 * @description: 字符串比大小
 * 字符串: a > b : 1  a == b : 0  a < b : -1
 * @param {*} a
 * @param {*} b
 * @return {*}
 * @author: zhj1214
 */
export const strSpecificSize = (a: string, b: string) => {
  if (!a || !b) return false;
  if (a.length >= b.length) {
    if (a.length > b.length) {
      return 1;
    } else {
      return a > b ? 1 : -1; // 长度相等
    }
  }
  return -1;
};

/**
 *
 * @param file File | Blob
 * @description 压缩图片
 * @returns Promise<Blob | File>
 */
export const compressImage = async (
  file: File | Blob
): Promise<Blob | File> => {
  return new Promise((resolve, reject) => {
    // new Compressor(file, {
    //   quality: 0.6,
    //   mimeType: "image/jpeg",
    //   success(result) {
    //     resolve(result);
    //   },
    //   error(err) {
    //     reject(err);
    //   },
    // });
  });
};

/**
 * @description: 获取环境配置信息
 * @return {*}
 * @author: zhj1214
 */
export function useEnvConfigInfo(): any {
  if (process.env.NODE_ENV != "development") return { token: "" };
  let WEB_NODE_ENV = "dev";
  try {
    WEB_NODE_ENV = useRuntimeConfig().public.WEB_NODE_ENV;
  } catch (error) {
    console.log("-环境信息-", process.env.WEB_NODE_ENV);
    WEB_NODE_ENV = process.env.WEB_NODE_ENV || "dev";
  }

  if (WEB_NODE_ENV === "dev" || WEB_NODE_ENV === "test") {
    return {
      token:
        // "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzY0MDc3NjU0ODIsInBheWxvYWQiOiJ7XCJ1aWRcIjoxODY4MjQ4NCxcIm1vYmlsZVwiOlwiMjAyMTIzNDY2QHFxLmNvbVwiLFwic2lkXCI6MTAwMTg2ODI0ODR9In0.V14udiZy0qMVggnXLJ1gnKBApTiSPNYaCZ77r0jqsNo", // berry@tradev-group.com
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzU4MTU4NDA1NTYsInBheWxvYWQiOiJ7XCJ1aWRcIjoxNTA0NDYsXCJtb2JpbGVcIjpcInpoajEyMTRAaG90bWFpbC5jb20udGVzdFwiLFwic2lkXCI6MTAwMDAxNTA0NDZ9In0.0nu_5onvfxm_TRuZBNkodEd_h35wXKauJG1HMnTMpSw", // zhj1214mail.com
      // "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzU5NjA3MzQ5MjUsInBheWxvYWQiOiJ7XCJ1aWRcIjoxODY4NTQ2NCxcIm1vYmlsZVwiOlwiMjAyMTIzNDk3NDYwQHFxLmNvbVwiLFwic2lkXCI6MTAwMTg2ODU0NjR9In0.9E6x4-S0cwgWqTSwul5zfUnV9P83MrC2sfpB-BqMjZc", // 202123497460@qq.com
      devProxy: "https://test-bdc.btcdana.org/api",
      // devProxy: "https://api.okmax.vip/",
      routeRules: "https://test-bdc.btcdana.org/api/**",
    };
  } else if (WEB_NODE_ENV === "pre" || WEB_NODE_ENV === "prep") {
    return {
      token:
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjUwNjg4MTIyNTYsInBheWxvYWQiOiJ7XCJ1aWRcIjoxODQxMzkyMyxcIm1vYmlsZVwiOlwiMTEzMDAwMzU4MjAwMjg1MDE0NzgzXCIsXCJzaWRcIjoxMDAxODQxMzkyM30ifQ.kFH9NYspcazgUAOG3txkK598ZlpoFf-AinDA5x3ZqRA", // zhj
      devProxy: "https://pre-bdc.btcdana.org/api",
      // devProxy: "https://api.dana668.com/",
      routeRules: "https://pre-bdc.btcdana.org/api/**",
    };
  } else if (WEB_NODE_ENV === "prod") {
    return {
      token:
        "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjUwNjg4MTIyNTYsInBheWxvYWQiOiJ7XCJ1aWRcIjoxODQxMzkyMyxcIm1vYmlsZVwiOlwiMTEzMDAwMzU4MjAwMjg1MDE0NzgzXCIsXCJzaWRcIjoxMDAxODQxMzkyM30ifQ.kFH9NYspcazgUAOG3txkK598ZlpoFf-AinDA5x3ZqRA", // zhj
      devProxy: "https://bdc.btcdana.org/api",
      routeRules: "https://bdc.btcdana.org/api/**",
    };
  }
  return { token: "" };
}
